<template>
  <div id="commissionPage">
    <BreadcrumbComponent :breadcrumbItems="breadcrumbItems" />
    <TableFilter :config="filterConfig" @search="handleSearch" />
    <!-- 工具欄 -->
    <a-sapce>
      <a-dropdown>
        <a-button type="primary" :loading="exportLoading">
          <template #icon>
            <ExportOutlined />
          </template>
          導出
        </a-button>
        <template #overlay>
          <a-menu @click="handleExport">
            <a-menu-item key="filteredData"> 按篩選導出 </a-menu-item>
            <a-menu-item key="allData"> 全部導出 </a-menu-item>
          </a-menu>
        </template>
      </a-dropdown>
    </a-sapce>
    <div class="data-box">
      <a-table
        :columns="columns"
        :data-source="tableData"
        :pagination="pagination"
        :loading="loading"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'shop'"
            >{{ record.shop?.name }}({{ record.shopId }})</template
          >
          <template v-if="column.dataIndex === 'doctorName'">{{
            record.doctor?.name
          }}</template>
          <template v-if="column.dataIndex === 'staffType'">
            <a-tag :bordered="false" color="green" v-if="record.staffType == 1"
              >合作</a-tag
            >
            <a-tag :bordered="false" color="blue" v-else>職員</a-tag>
          </template>
          <template v-if="column.dataIndex === 'totalSales'">
            $ {{ Number(record.totalSales).toLocaleString() }}
          </template>
          <template v-if="column.dataIndex === 'totalCommission'">
            <template v-if="isDoctor && !record.isArchived">待計算</template>
            <template v-else>
              $ {{ Number(record.totalCommission).toLocaleString() }}
            </template>
          </template>
          <!-- isArchived -->
          <template v-if="column.dataIndex === 'isArchived'">
            <a-tag
              :bordered="false"
              color="success"
              v-if="record.isArchived == true"
              >已歸檔</a-tag
            >
            <a-tag :bordered="false" color="processing" v-else>未歸檔</a-tag>
          </template>
          <template v-if="column.dataIndex === 'updatedAt'">
            {{ $formatDate(record.updatedAt) }}
          </template>
          <template v-if="column.key === 'action'">
            <a-button @click="handleView(record)">明細</a-button>
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import { message } from "ant-design-vue";
import { ExportOutlined } from "@ant-design/icons-vue";
import BreadcrumbComponent from "@/components/BreadcrumbComponent.vue";
import TableFilter from "@/components/TableFilter.vue";
import { tableColumns, filterFields } from "@/models/commission";
import { createPagination } from "@/utils/pagination";
import { commissionApi } from "@/api";
import { useRouter, useRoute } from "vue-router";
import { watchRouteQuery } from "@/utils/routeQueryWatcherUtil";
import { useAuthUserStore } from "@/store/authUserStore";

const breadcrumbItems = [{ url: "", name: "佣金管理" }];
const columns = tableColumns;
const filterConfig = filterFields;
const router = useRouter();
const route = useRoute();

const pagination = createPagination();

const tableData = ref([]);

const userInfo = useAuthUserStore().userInfo;
const isDoctor = userInfo.roles.includes("Doctor");

const loading = ref(false);
const fetchData = async (params?: any) => {
  try {
    loading.value = true;
    const {
      data: { list, page, limit, total },
    } = await commissionApi.getCommissionList(params);
    tableData.value = list || [];
    pagination.updatePagination(page, limit, total);
  } catch (error) {
    console.error("獲取佣金列表失敗", error);
  } finally {
    loading.value = false;
  }
};

// 監聽路由變化
watchRouteQuery(fetchData);

const handleSearch = (params: any) => {
  router.push({ query: params });
};

// 編輯

const handleView = (record: any) => {
  router.push({ name: "CommissionDetail", params: { id: record.id } });
};

// 導出
const exportLoading = ref(false);
const handleExport = async ({ key }: { key: string }) => {
  let params: any = {};
  if (key === "filteredData") {
    params = route.query;
  }
  exportLoading.value = true;
  try {
    await commissionApi.exportCommissionList(params);
  } catch (error) {
    message.error("導出數據失敗");
  } finally {
    exportLoading.value = false;
  }
};
</script>

<style scoped></style>
